package com.bkitmobile.kesu.appengine.storingdata.server.entity;

import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.GeoPt;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
@PersistenceCapable
public class UserLocationData {
	@PrimaryKey
	@Persistent
	private Key key;
	
	@Persistent(serialized = "true")
    private List<LocationData> locationData;

	@Persistent(serialized = "true")
	private LocationData currentStatus;
	
	@Persistent
	private Set<Key> usersView;
	
	
	private static final int NUMBER_OF_LOCATION = 200;
	private static final int MIN_DISTANCE = 20;
	public UserLocationData(String user)
	{
		key = KeyFactory.createKey(UserLocationData.class.getSimpleName(),user);
		locationData = new LinkedList<LocationData>();
		setCurrentStatus(null);
	}
	public void setKey(Key key) {
		this.key = key;
	}
	public void addNewLocation(double latitude,double longitude,String status,boolean isFirst)
	{
		LocationData tmp = new LocationData(latitude,longitude, status,isFirst);
		if (locationData.size()>0)
		{
			if (locationData.get(0).isFirst())
			{
				locationData.remove(0);
				locationData.add(0,tmp);
			}else {
				double disLong = (tmp.getLongitude()-locationData.get(0).getLongitude())*1853*60;
				double disLat = (tmp.getLatitude()-locationData.get(0).getLatitude())*1853*60;
				double distance = Math.sqrt(Math.pow(disLong, 2)+Math.pow(disLat, 2));
				if (distance > MIN_DISTANCE || status != null) locationData.add(0,tmp);
			}
		}
		else locationData.add(0,tmp);
		int size = locationData.size();
		for (int i = size-1; i >= 0 ; i--)
		{
			Date oldTime = locationData.get(i).getDate();
			if (new Date().getTime() - oldTime.getTime()>3600*1000*24)
				locationData.remove(i);
			else break;
		}
		
		size = locationData.size();
		if (size>NUMBER_OF_LOCATION)
			for (int i = size-1 ; i >= NUMBER_OF_LOCATION-1;i--)
				locationData.remove(i);
		if (status != null) setCurrentStatus(tmp);
	}

	public Key getKey() {
		return key;
	}


	public void setLocationData(List<LocationData> locationData) {
		this.locationData = locationData;
	}


	public List<LocationData> getLocationData() {
		return locationData;
	}
	public void setCurrentStatus(LocationData currentStatus) {
		this.currentStatus = currentStatus;
	}
	public LocationData getCurrentStatus() {
		return currentStatus;
	}
	public void setUsersView(Set<Key> usersView) {
		this.usersView = usersView;
	}
	public Set<Key> getUsersView() {
		return usersView;
	}
}
